package com.xyht.sca_s.student_manage_system.modules.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.user.mapper.SmsUserMapper;
import com.xyht.sca_s.student_manage_system.modules.wx.entity.WxMpCodeEntity;
import com.xyht.sca_s.student_manage_system.modules.wx.entity.WxMpPropertiesEntity;
import com.xyht.sca_s.student_manage_system.modules.wx.service.WXMpService;
import com.xyht.sca_s.student_manage_system.modules.wx.util.WeChatUtil;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.util.List;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.wx.constant.CommonConstant.BOOLEAN_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.wx.constant.CommonConstant.BOOLEAN_TRUE;

@RestController
@RequestMapping("/wx/mp")
@Log4j2
public class WXMpController {
    @Autowired
    private WeChatUtil weChatUtil;
    @Autowired
    private SmsUserMapper smsUserMapper;
    @Autowired
    private WxMpPropertiesEntity wxMpPropertiesEntity;
    @Autowired
    private WXMpService wxMpService;

    @RequestMapping("/test")
    public void test123(HttpServletRequest request,PrintWriter pw){
        try{
            wxMpService.receiveUserPushEvent(request,pw);
//            String testStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
//                    "<xml>\n" +
//                    "<ToUserName><![CDATA[gh_f01366ee178c]]></ToUserName>\n" +
//                    "<Encrypt><![CDATA[p+9RhV6usVyTsi6Z+dCXPrgR48KcEgZkppFoeEFPy1/cjLQPup9L9tHhbgqKVX0lxcXgYH07RoGteE68N6TQ0F6iBZsaM4nLkSyJoz9gzR2KqR0u93pdJCSLEYHNx5QnkT2zJaeWt73tn9gf37/C7R0ssE8JMC4TT27kNtFoaxoN33zv0oVXk1NzJ8qp3T/rM38AUg9+v1Kx1su3SVhL354LqExGwLKsjFtetprpZUXAQ/jyOQyVzY1Zlyj47tJAjyYguZ8GS1JgwdD3jtUcOjcSDtiXNfeOqE99YqLrETjSqYRBNArQME++gR0cQLn6vIpzNi3CF2Wpl/Nspq+VY3a5/urXjtY25ryxfjdlpvJAt1JulE0PjOxlMlldc1TuLWJrPsuS+zzB6aIo9d1rCr8+wgM7v6dj/CpY0R7vWug=]]></Encrypt>\n" +
//                    "</xml>";
//            String result = weChatUtil.decryptMsg("","","",testStr);
//            return result;
        }catch (Exception e){
        }
    }

    @PostMapping("/bindMa")
    public ResponseResult bindMaUserInfo(@RequestBody @Validated WxMpCodeEntity code) {
        try {
            log.debug("+++++++++++"+code.getCode());
            WxMpUser result = weChatUtil.getWXMpOAuth2AccessToken(code.getCode());
            String open_id = result.getOpenId();
            String union_id = result.getUnionId();
            log.debug("++++++++++"+open_id);
            log.debug("++++++++++"+union_id);
            if (!isNullOrEmpty(open_id) && !isNullOrEmpty(union_id)) {
                List<SmsUser> userList = smsUserMapper.selectList(new QueryWrapper<SmsUser>()
                        .lambda()
                        .eq(SmsUser::getWxUnionId, union_id));
                if (userList == null || userList.size() < 1) {
                    return CommonResult.failed(CommonCodeEnum.WX_MA_NOT_REGISTER_ACCOUNT);
                }
                for (SmsUser smsUser:userList) {
                    if (smsUser.getIsMpBind() == BOOLEAN_FALSE){
                        SmsUser updateUser = new SmsUser();
                        updateUser.setId(smsUser.getId());
                        updateUser.setIsMpBind(BOOLEAN_TRUE);
                        updateUser.setIsMessage(BOOLEAN_TRUE);
                        updateUser.setWxMpId(open_id);

                        smsUserMapper.updateById(updateUser);
                    }
                }
            } else {
                return CommonResult.failed(CommonCodeEnum.WX_MP_BIND_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.WX_MP_BIND_FAIL);
        }
        return CommonResult.success();
    }

    @GetMapping("/receive")
    public void receiveUserPushEventGET(HttpServletRequest request,  PrintWriter pw) {
        // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (weChatUtil.checkWXSign(request)) {
            pw.write(request.getParameter("echostr"));
        } else {
            pw.write("");
        }
    }

    @PostMapping("/receive")
    public void receiveUserPushEventPOST(HttpServletRequest request,  PrintWriter pw) {
        log.debug("++++++++"+ JSONObject.toJSONString(request.getParameterMap()));
        // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (weChatUtil.checkWXSign(request)) {
            wxMpService.receiveUserPushEvent(request,pw);

        } else {
            log.debug("失败||||||||||||");
            pw.write("");
        }
    }




}
